/*
 * Written by Anders Fongen
 * Norwegian Defence Research Establishment (FFI)
 * Email: anders@fongen.no
 */

package no.ffi.gismoidm.idp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author anf
 * Created on 16.jul.2009
 */
public class Config {
    
    static java.util.Properties props;
    static String fileName;
    public static final String SIGNATURE_ALGORITHM="sha1withrsa";
    public static final String ENCRYPTION_ALGORITHM="rsa";
    public static final String SYMMETRIC_CRYPTO_ALGORITHM="aes";

    public static void loadPropertiesFrom(String filename) {
        if (props!=null) return; // Initialize only once
        
        props = new Properties();
        if (filename==null || filename.equals(""))
            filename = System.getProperty("GISMOIDM.CONFIG",System.getProperty("user.home") + "/config/gismoidm.properties");
            System.out.println("Config(null) initialize filename to "+filename);
            Config.fileName=filename;
        try {
            FileInputStream f = new FileInputStream(filename);
            props.load(f);
            System.out.println("Properties loaded from " + filename + ":");
            props.list(System.out);
        } catch (Exception e) { 
            System.out.println("Unable to load property file, set property JIDM.CONFIG");
            System.out.println("(present value is -->" + filename + "<--");
            e.printStackTrace(); 
        }
        
    }

    public static void setProperty(String name,String value){
        if (props==null) System.out.println("Props er null!");
        props.setProperty(name, value);
        System.out.println("The property "+name+" has been updated with value "+ value);
       
        try {
            FileOutputStream file = new FileOutputStream(fileName); 
            props.store(file,"Updated "+name);
            /*FileInputStream f = new FileInputStream(fileName);
            props.load(f);
            System.out.println("Properties loaded after update");
            props.list(System.out);
            f.close();*/
            file.close();
        } catch (IOException ex) {
            Logger.getLogger(no.ffi.tpm.Config.class.getName()).log(Level.SEVERE, null, ex);
        } 
                
                
        
    }
    
    public static String getProperty(String name) {
        return getProperty(name,null);
    }
    
    public static String getProperty(String name, String def) {
        if (props==null) System.out.println("Props er null!");
        String s = props.getProperty(name, def);
        if (s == null) { 
            System.out.println("Null retur for " + name + " property");return null;
        }
        else return s.trim();
    }
    
}
